//
//  NSData+XOR.m
//  PigMarket
//
//  Created by Felix on 2019/4/11.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "NSData+XOR.h"

@implementation NSData (XOR)

- (NSData *)xorWithStringKey:(NSString *)key {
    
    NSMutableData *mutableData = [NSMutableData data];
    mutableData.data = self;
    
    NSData* keyBytes = [key dataUsingEncoding:NSUTF8StringEncoding];
    Byte* keyByte = (Byte *)[keyBytes bytes];
    
    Byte* dataBuffer = (Byte *)[mutableData mutableBytes];
    
    int keyIndex = 0;
    
    for (int x = 0; x < [self length]; x++) {
        dataBuffer[x]  = dataBuffer[x] ^ keyByte[keyIndex];
        if (++keyIndex == [keyBytes length]) {
            keyIndex = 0;
        }
    }
    
    return mutableData;
    
}

- (NSData *)xorWithDataKey:(NSData *)key {
    NSMutableData *mutableData = [NSMutableData data];
    mutableData.data = self;
    
    Byte* keyByte = (Byte *)[key bytes];
    
    Byte* dataBuffer = (Byte *)[mutableData mutableBytes];
    
    int keyIndex = 0;
    
    for (int x = 0; x < [self length]; x++) {
        dataBuffer[x]  = dataBuffer[x] ^ keyByte[keyIndex];
        if (++keyIndex == [key length]) {
            keyIndex = 0;
        }
    }
    
    return mutableData;
}

@end
